package com.ruoyi.framework.web.service;

import javax.annotation.Resource;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.utils.RedisUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.BlackListException;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.exception.user.UserNotExistsException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 登录校验方法
 * 
 * @author ruoyi
 */
@Component
public class SysLoginService
{
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;




    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {
        // 验证码校验
        validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        finally
        {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        String s = userService.selectUserRoleGroup(username);


        if (s.contains("工作人员")){
            return "无权限";
        }
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled)
        {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            if (captcha == null)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            if (!code.equalsIgnoreCase(captcha))
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }


    /**
     * 微信登录
     *
     * 备注：本来想用unionid作为唯一标识的，但是，小程序需要绑定微信开放平台，并且需要500大洋，我没钱，所以，就用openid作为唯一标识了。
     * @param decryptResult 登录凭证 只能用一次
     * @return
     */
    public String wxLogin(String decryptResult){
        //字符串转json
        JSONObject jsonObject = JSONObject.parseObject(decryptResult);
        //获取openid,这里本可以获取unionid的,可惜没钱
        String unionid = jsonObject.getString("unionid");
        String openId = jsonObject.getString("openId");
        //获取nickName
        String nickName = jsonObject.getString("nickName");
        //获取头像
        String avatarUrl = jsonObject.getString("avatarUrl");
        //还可以获取其他信息
        //根据openid判断数据库中是否有该用户
        //根据openid查询用户信息
        SysUser wxUser = userMapper.selectWxUserByOpenId(openId);

        //如果查不到，则新增，查到了，则更新
        SysUser user = new SysUser();
        if (wxUser == null) {
            // 新增
            // 设置姓名 ，默认使用昵称+随机数，防止重复姓名的发生 数据库中把username的长度修改的长一点
           /* user.setUserName(IdUtils.fastSimpleUUID());
            user.setNickName(nickName);
            //数据库中把长度修改的长一点
            user.setAvatar(avatarUrl);
            // 如果有unionid，则设置unionid
            // wxUser.setUnionId(unionid);
            user.setOpenId(openId);
            user.setCreateTime(DateUtils.getNowDate());
            //新增 用户
            userMapper.insertUser(user);*/
            return "openid+"+openId;
        }else {
            //更新
            user = wxUser;
           // user.setNickName(nickName);
           // user.setAvatar(avatarUrl);
           // user.setUpdateTime(DateUtils.getNowDate());
           // userMapper.updateUser(user);
        }

        //组装token信息
        LoginUser loginUser = new LoginUser();
        loginUser.setOpenId(openId);
        //如果有的话设置
//        loginUser.setUnionId(unionid);
        loginUser.setUser(user);
        loginUser.setUserId(user.getUserId());

        // 生成token
        return tokenService.createToken(loginUser);
    }

    public String wxLoginphone(String openid,String phone,String photoUrl,String unionid){
        //获取openid,这里本可以获取unionid的,可惜没钱
//        String unionid = jsonObject.getString("unionid");
 /*       String openId = jsonObject.getString("openId");
        //获取nickName
        String nickName = jsonObject.getString("nickName");
        //获取头像
        String avatarUrl = jsonObject.getString("avatarUrl");*/
        //还可以获取其他信息
        //根据openid判断数据库中是否有该用户
        //根据openid查询用户信息
        SysUser wxUser = userMapper.selectWxUserByOpenId(openid);
        //如果查不到，则新增，查到了，则更新
        SysUser user = new SysUser();
        if (wxUser == null) {
            // 新增
            // 设置姓名 ，默认使用昵称+随机数，防止重复姓名的发生 数据库中把username的长度修改的长一点
          /*  user.setUserName(IdUtils.fastSimpleUUID());
            user.setNickName(nickName);
            //数据库中把长度修改的长一点
            user.setAvatar(avatarUrl);
            // 如果有unionid，则设置unionid
            // wxUser.setUnionId(unionid);
            user.setOpenId(openId);
            user.setCreateTime(DateUtils.getNowDate());
            //新增 用户
            userMapper.insertUser(user);*/
            user = userMapper.selectWxUserByPhone(phone);
            //如果为null  没有信息
            if (user == null){
                return null;
            }else {

                //在这里存unionid
                user.setAvatar(photoUrl);
                user.setOpenId(openid);
                user.setUnionId(unionid);
                user.setUpdateTime(DateUtils.getNowDate());
                userMapper.updateUser(user);
               // getGzhOpenid();
                /*
                 * 通过电话查找userid 查到角色是支局长的 更新Gzhopenid
                 * */
                List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectUserRoleByUserId(user.getUserId());
                if (Objects.nonNull(sysUserRoles) && sysUserRoles.size() > 0){
                    if(sysUserRoles.get(0).getRoleId() == 101){
                        getGzhOpenid();
                    }
                }
            }
        }else {
            //更新
            user = wxUser;
            /*user.setNickName(nickName);
            user.setAvatar(avatarUrl);
            user.setUpdateTime(DateUtils.getNowDate());
            userMapper.updateUser(user);*/
        }

        //组装token信息
        LoginUser loginUser = new LoginUser();
        loginUser.setOpenId(openid);
        //如果有的话设置
      // loginUser.setUnionId(unionid);
        loginUser.setUser(user);
        loginUser.setUserId(user.getUserId());

        // 生成token
        return tokenService.createToken(loginUser);
    }


    public  void  getGzhOpenid() {
        String access_token = String.valueOf(redisUtils.get("access_token"));
        String url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token="+access_token;
        if(restTemplate==null){
            restTemplate = new RestTemplate();
        }
        String res = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONObject.parseObject(res);

        //获取公众号用户列表
        String data = jsonObject.getString("data");
        JSONObject dataJson = JSONObject.parseObject(data);
        String openid = dataJson.getString("openid");
        JSONArray objects = JSONUtil.parseArray(openid);
        List<String> strings = JSONUtil.toList(objects, String.class);

        //获取用户列表
        //List<SysUser> sysUsers = userService.selectUserListOpen(new SysUser());
        List<SysUser> sysUsers = userService.list();
        List<String> collect = sysUsers.stream().filter(x-> Objects.nonNull(x.getUnionId())).map(SysUser::getUnionId).collect(Collectors.toList());

        //两个集合求交集
        List<String> resultList = new ArrayList<>();
        strings.stream().forEach(a1->{
            if (collect.contains(a1)){
                resultList.add(a1);
            }
        });
        //两个集合求差
        Collection<String> disjunction = CollectionUtil.disjunction(strings, resultList);
        List<String> collect1 = disjunction.stream().collect(Collectors.toList());

        //获取用户的unionid
        if (Objects.nonNull(collect1)&&collect1.size()>0){
            ArrayList<Map<String, String>> maps = new ArrayList<>();
            for (String id : collect1) {
                String url1 = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+access_token+"&openid="+id+"&lang=zh_CN";
                if(restTemplate==null){
                    restTemplate = new RestTemplate();
                }
                String res1 = restTemplate.getForObject(url1, String.class);
                JSONObject jsonObject1 = JSONObject.parseObject(res1);
                //获取unionid
                String unionid = jsonObject1.getString("unionid");
                //HashMap<String, String> map = new HashMap<>();
                //map.put("unionid", unionid);
                //map.put("openid", id);
                //maps.add(map);


                //去数据库查询对应的unionid
               /* QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(SysUser::getUnionId, unionid);*/
               /* SysUser sysUser = new SysUser();
                sysUser.setUnionId(unionid);*/

                if (Objects.nonNull(unionid)){
                    QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(SysUser::getUnionId, unionid);
                    List<SysUser> list = userService.list(queryWrapper);
                    if (Objects.nonNull(list) && list.size()>0){
                        SysUser user = list.get(0);
                        user.setGzhopenId(id);
                        // userService.updateUser(user);
                        QueryWrapper<SysUser> queryWrapper1 = new QueryWrapper<>();
                        queryWrapper1.lambda().eq(SysUser::getUserId, user.getUserId());
                        userService.update(user, queryWrapper1);
                    }

                }
               /* List<SysUser> sysUsers1 = userService.selectUserListOpen(sysUser);
                // List<SysUser> sysUsers1 = userService.list(queryWrapper);
                if (sysUsers1.size()>0){
                    sysUsers1.get(0).setGzhopenId(id);
                    userService.updateUser(sysUsers1.get(0));
                }*/
            }
        }

    }
}
